import { CustomRoute, GlobalMenuOption } from '@/interface'
import { dynamicIconRender } from '@/utils'
import { customRoutes } from './routes'

/** 判断路由是否作为菜单 */
function asMenu(route: CustomRoute) {
  return !route.meta?.notMenu
}

function transformRouteToMenu(routes: CustomRoute[] | undefined) {
  if (routes === undefined || routes.length === 0) return undefined
  const globalMenu: GlobalMenuOption[] = []
  routes
    //.filter((route) => route.meta.notMenu !== true)
    .forEach((route) => {
      const { name, path, meta, children } = route
      const { icon, title } = meta
      const routeName = name as string
      const menuChildren = transformRouteToMenu(children as CustomRoute[])
      const menuItem: GlobalMenuOption = {
        label: title ?? routeName,
        key: routeName,
        routeName,
        routePath: path,
      }
      if (icon) menuItem.icon = dynamicIconRender(icon)
      if (menuChildren) menuItem.children = menuChildren
      if (asMenu(route)) {
        globalMenu.push(menuItem)
      } else if (menuChildren) {
        globalMenu.push(...menuChildren)
      }
    })
  if (globalMenu.length === 0) return undefined
  return globalMenu
}

export const menus = transformRouteToMenu(customRoutes)
